<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <!--顶部搜索 -->
      <div class="top-operate-default flex-col" style="align-items: baseline; padding: 20px 0; height: 100%; ">
        <div class="search-item">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" class="search-item">
            <el-form-item label="搜索订单：" style="margin-bottom:0px">
              <el-select v-model="queryParams.textCol">
                <el-option label="订单号" value="orderNo"></el-option>
                <el-option label="配送地址" value="customerAddress"></el-option>
                <el-option label="自提地址" value="memberTakeAddress"></el-option>
                <el-option label="顾客姓名" value="customerNickname"></el-option>
                <el-option label="顾客手机" value="customerPhone"></el-option>
                <!-- 			<el-option label="门店名称" value="storeName"></el-option>
								<el-option label="门店账号" value="memberPhone"></el-option> -->
              </el-select>
              <el-input v-model="queryParams.textValue" placeholder="请输入搜索内容" style="width: 200px">
              </el-input>
            </el-form-item>
            <el-form-item label="订单类型：" style="margin-bottom:0px">
              <el-select v-model="queryParams.deliveryMode" placeholder="请选择" class="takeSelect">
                <el-option v-for="item in storeOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间筛选：" style="margin-bottom:0px">
              <el-select class="pad-l-10" v-model="dateColumn">
                <el-option v-for="item in searchOrderTimeTypeList" :key="item.value" :label="item.label"
                  :value="item.value"> </el-option>
              </el-select>
              <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="v-align-c total-bar mar-t-20">
        <div class="flex-item text-align-c total-bar-item">
          <div class="font-28 font-w font-orange">{{turnover}}</div>
          <div class="font-16 mar-t-16 color-96">成交量（件）</div>
        </div>
        <div class="flex-item text-align-c total-bar-item">
          <div class="font-28 font-w font-orange">{{transactionAmount}}</div>
          <div class="font-16 mar-t-16 color-96">成交额（元）</div>
        </div>
        <div class="flex-item text-align-c total-bar-item">
          <div class="font-28 font-w font-orange">{{perTicketSales}}</div>
          <div class="font-16 mar-t-16 color-96">人均消费（元）</div>
        </div>
      </div>
      <div class="tabs-box mar-t-15">
        <!--订单状态 -2: 已付款取消 -1: 未付款取消 0: 未付款, 1: 已付款 2: 已发货 3: 已收货 4: 已完成 -->
        <!--待配货对应已付款，待提货对应已发货，已提货对应已收货 -->
        <el-tabs type="card" v-model="orderStatus" @tab-click="doChangeTab">
          <el-tab-pane v-for="item in orderStatusLabels" :key="item.name" :label="item.title" :name="item.name">
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 全选、操作 -->
      <div class="pad-t-15 pad-b-15 font-14 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
            class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-button @click="exportOrder">批量导出</el-button>
      </div>
      <el-table ref="multipleTable" :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中" style="width: 100%;">
        <el-table-column width="50px" type="selection"></el-table-column>

        <el-table-column width="200px" label="订单号" prop="orderNo"></el-table-column>
        <el-table-column width="200px" label="订单类型" prop="deliveryType" :formatter="deliveryTypeFormat">
        </el-table-column>
        <el-table-column width="200px" label="配送地址/自提地址" prop="memberTakeAddress" :formatter="takeAddressFormat">
        </el-table-column>
        <el-table-column width="180px" label="顾客信息">
          <template slot-scope="scope">
            <div v-if="scope.row.customerNickname">
              <div>{{scope.row.customerNickname}}</div>
              <div v-if="scope.row.customerPhone">{{scope.row.customerPhone}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="120px" label="数量" prop="goodsNum">
        </el-table-column>
        <el-table-column width="150px" label="实付金额" prop="actualPrice" v-if="getVersionType() != 2">
          <template slot-scope="scope">
            <div v-if="scope.row.actualPrice">
              <div>￥{{scope.row.actualPrice}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="150px" label="实收金额" prop="enterpriseAmount" v-if="getVersionType() != 2">
          <template slot-scope="scope">
            <div v-if="scope.row.enterpriseAmount">
              <div>￥{{scope.row.enterpriseAmount}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="200px">
          <template slot="header" slot-scope="scope">
            <span>{{orderTimeColName}}</span>
          </template>
          <template slot-scope="scope">
            {{ scope.row[queryParams.dateColumn]}}
          </template>
        </el-table-column>
        <el-table-column width="130px" label="订单状态" :formatter="orderStatusFormat">
        </el-table-column>
        <el-table-column min-width="80px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.size"
        @pagination="getList" />
    </div>
  </div>
</template>

<script>
  import {
    pageProjectOrder,
    statProjectOrder,
    getStatisticsStoreOrderInfo
  } from '@/api/goods/order'
  import {
    getPromotionForSelControlList
  } from '@/api/sell/promotion'
  import {
    downloadFile
  } from '@/api/common/common'
  export default {
    data() {
      return {
        storeOptions: [{
          value: 'allDeliveryModel',
          label: '全部'
        }, {
          value: 'communityGroupExtraction',
          label: '社区团购'
        }, {
          value: 'storeExtraction',
          label: '到店自提'
        }, {
          value: 'homeDelivery',
          label: '配送上门'
        }],
        orderStatus: '100',
        memberId: '',
        // 数据字典
        dict: {
          orderStatus: {}
        },
        turnover: '0',
        transactionAmount: '0.00',
        perTicketSales: '0.00',
        // 文本model
        // textCol: 'orderNo',
        textValue: '',
        allChecked: false,
        // 选择订单id
        selectOrderId: '',
        // 选中订单id集合
        selectOrderIds: [],
        dateColumn: 'payTime',
        dateRange: [],
        dataList: [],
        total: 0,
        multipleSelection: [],
        listLoading: true,
        orderTimeColName: '',
        queryParams: {
          currentPage: 1,
          size: 10,
          dateColumn: 'payTime',
          orderType: 30,
          // deliveryType: 3,
          textCol: 'orderNo',
          deliveryStatus: -1,
          deliveryMode: 'allDeliveryModel',
          deliveryTypeList: '3, 4, 5'
        },
        // 订单时间搜索类型
        searchOrderTimeTypeList: [{
          value: 'createTime',
          label: '下单时间'
        }, {
          value: 'payTime',
          label: '付款时间'
        }, {
          value: 'deliveryTime',
          label: '发货时间'
        }, {
          value: 'receivedTime',
          label: '收货时间'
        }, {
          value: 'cancelTime',
          label: '取消时间'
        }, {
          value: 'completeTime',
          label: '完成时间'
        }],
        orderSourceActivityOptions: [],
        // 待配货对应已付款，待提货对应已发货，已提货对应已收货
        orderStatusLabels: [{
          name: '100',
          title: '全部(0)'
        }, {
          name: '1',
          title: '待配送(0)'
        }, {
          name: '2',
          title: '待收货(0)'
        }, {
          name: '3',
          title: '已收货(0)'
        }, {
          name: '0',
          title: '待付款(0)'
        }, {
          name: '4',
          title: '已完成(0)'
        }, {
          name: '-1',
          title: '已取消(0)'
        }]
      }
    },
    computed: {},
    created() {
      const queryParams = this.getCurrentPage().query
      if (queryParams.memberId) {
        this.memberId = queryParams.memberId
      }
      if (queryParams.promotionId) {
        this.queryParams.promotionId = queryParams.promotionId
      }

      this.getList()
      this.getPromotionForSelControlList()
      this.getStatisticsStoreOrderInfo()
    },
    methods: {
      doCount() {
        this.count = this.count + 1
      },
      doSearch() {
        this.queryParams.currentPage = 1
        this.getList()
      },
      doResetSearch() {
        const originData = this.$options.data()
        this.dateRange = []
        this.dateColumn = originData.dateColumn
        if (this.$refs['queryForm']) {
          this.$refs['queryForm'].resetFields()
        }
        this.queryParams = originData.queryParams
        this.doSearch()
      },
      doChangeTab(val) {
        this.doSearch()
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.dataList.length) {
          this.dataList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.dataList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 设置查询条件
      setQueryParams() {
        switch (this.orderStatus * 1) {
          default:
            this.queryParams.orderStatus = this.orderStatus
            this.queryParams.orderStatusList = ''
            break
          case -2:
            this.queryParams.orderStatus = ''
            this.queryParams.orderStatusList = '-1,-2'
            break
          case 100:
            this.queryParams.orderStatus = ''
            this.queryParams.orderStatusList = ''
            break
        }
        this.orderTimeColName = this.searchOrderTimeTypeList.filter(item => {
          return item.value.indexOf(this.dateColumn.trim()) >= 0
        })[0].label
        this.queryParams.enterpriseId = this.getEnterpriseId()
        this.queryParams[this.queryParams.textCol] = this.queryParams.textValue
        this.queryParams.startDate = (this.dateRange && this.dateRange.length > 0) ? this.dateRange[0] : ''
        this.queryParams.endDate = (this.dateRange && this.dateRange.length > 1) ? this.dateRange[1] : ''
        this.queryParams.memberId = this.memberId
        this.queryParams.dateColumn = this.dateColumn
        this.queryParams.activityType = 2
      },
      deliveryTypeFormat(row, colomn) {
        var actions = []
        if (row.deliveryType === 3) {
          actions.push('社区团购')
        }
        if (row.deliveryType === 4) {
          actions.push('到店自提')
        }
        if (row.deliveryType === 5) {
          actions.push('配送上门')
        }
        return actions.join('')
      },
      takeAddressFormat(row, colomn) {
        var actions = []
        if (row.deliveryType === 3 || row.deliveryType === 4) {
          actions.push(row.memberTakeStoreName)
        }
        if (row.deliveryType === 5) {
          actions.push(row.customerAddress)
        }
        return actions.join('')
      },
      getList() {
        this.listLoading = true
        this.setQueryParams()
        this.queryParams.deliveryTypeList = ''
        this.queryParams.memberId = this.getMemberId()
        if (this.queryParams.deliveryMode === 'allDeliveryModel') {
          this.queryParams.deliveryTypeList = '3, 4, 5'
        } else if (this.queryParams.deliveryMode === 'homeDelivery') {
          this.queryParams.deliveryTypeList = '5'
        } else if (this.queryParams.deliveryMode === 'storeExtraction') {
          this.queryParams.deliveryTypeList = '4'
        } else if (this.queryParams.deliveryMode === 'communityGroupExtraction') {
          this.queryParams.deliveryTypeList = '3'
        }
        this.statOrder()
        pageProjectOrder(this.queryParams).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.dict = response.data.dict
          this.queryParams[this.queryParams.textCol] = ''
        })
      },
      // 统计门店全部订单信息
      getStatisticsStoreOrderInfo() {
        const that = this
        const params = {}
        params.orderType = that.queryParams.orderType
        params.enterpriseId = this.getEnterpriseId()
        params.memberId = this.getMemberId()
        params.deliveryTypeList = '3, 4, 5'
        getStatisticsStoreOrderInfo(params).then(response => {
          if (response.isError) return
          console.log(response)
          this.turnover = response.data.turnover
          this.transactionAmount = response.data.transactionAmount
          this.perTicketSales = response.data.perTicketSales
        })
      },
      // 统计订单
      statOrder() {
        const that = this
        statProjectOrder({
          enterpriseId: that.getEnterpriseId(),
          orderType: that.queryParams.orderType,
          memberId: this.getMemberId(),
          deliveryTypeList: this.queryParams.deliveryTypeList
        }).then(response => {
          if (response.isError) return
          // 待配货对应已付款待发货，待提货对应已发货待收货，已提货对应已收货
          for (let i = 0; i < that.orderStatusLabels.length; i++) {
            const title = that.orderStatusLabels[i].title
            const name = that.orderStatusLabels[i].name
            if (name === '-1') {
              let cancelNum = 0
              if (response.data[-1] && response.data[-1] > 0) {
                cancelNum = response.data[-1]
              }
              if (response.data[-2] && response.data[-2] > 0) {
                cancelNum = cancelNum + response.data[-2]
              }
              that.orderStatusLabels[i].title = title.replace('(0)', '(' + cancelNum + ')')
            } else {
              that.orderStatusLabels[i].title = title.replace('(0)', '(' + response.data[name] + ')')
            }
          }
        })
      },
      getPromotionForSelControlList() {
        const that = this
        const params = {}
        params.userType = 1
        params.userId = this.getEnterpriseId()
        params.activityType = 2
        getPromotionForSelControlList(params).then(response => {
          if (response.isError) return
          that.orderSourceActivityOptions = response.data
        })
      },
      // 跳转订单详情
      doLinkDetail(row) {
        this.$router.push({
          path: '/order/store/detail/index',
          query: {
            orderId: row.orderId
          }
        })
      },
      exportOrder() {
        if (this.multipleSelection.length > 0) {
          const orderIds = this.multipleSelection.map(item => item.orderId)
          downloadFile('/goods/projectOrder/exportStoreOrderData', {
            enterpriseId: this.getEnterpriseId(),
            deliveryType: this.queryParams.deliveryType,
            orderIds: orderIds.join(',')
          }, '门店订单.xlsx')
        } else {
          this.setQueryParams()
          this.queryParams.memberId = this.getMemberId()
          downloadFile('/goods/projectOrder/exportStoreOrderData', this.queryParams, '门店订单.xlsx')
        }
      },
      orderStatusFormat(row) {
        if (row.orderStatus === 1) {
          return '待配货'
        }
        if (row.orderStatus === 2) {
          return '待提货'
        }
        if (row.orderStatus === 3) {
          return '已提货'
        }
        return this.dict.orderStatus[row.orderStatus]
      }
    }
  }
</script>

<style>
  .orderSourceActivity {
    width: 200px !important;
  }

  .orderSourceActivity .el-input {
    width: 200px !important;
  }
</style>
<style lang="less" scoped>
  .user-avatar {
    width: 65px;
    height: 65px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .takeSelect {
    /deep/.el-input {
      width: 160px;
    }
  }

  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }
</style>
